<template>
  <el-dialog :title="checkTitle" :visible="showDialog" @opened="limit" @close="btnCancel">
    <el-form ref="form" :model="formDate" :rules="rules">
      <!-- 下拉框 -->
      <el-form-item label="分类" prop="category">
        <el-select ref="category" v-model="formDate.category" :clearable="isClearable" placeholder="请选择" style="margin-right:5px">
          <!-- <el-option value="全部分类" /> -->
          <el-option
            v-for="item in formData1"
            :key="item.id"
            :label="item.title"
            :value="item.id"
          />
        </el-select></el-form-item>
      <el-form-item label="经纪:" prop="agent">
        <el-select v-model="formDate.agent" :clearable="isClearable" placeholder="请选择" style="margin-right:5px">
          <!-- <el-option value="全部经纪" /> -->
          <el-option
            v-for="item in formData"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <!-- 标题 -->
      <el-form-item label="标题:" prop="title">
        <el-input v-model="formDate.title" style="width:800px" />
      </el-form-item>
      <!-- 标签 -->
      <el-form-item label="标签:" prop="tags">
        <el-input v-model="formDate.tags" style="width:100px" />
      </el-form-item>
      <!-- 地址 -->
      <el-form-item label="地址:" prop="address">
        <el-cascader
          v-model="address"
          :options="list"
          @change="handleChange"
        />
        <el-input v-model="formDate.address" style="width:300px" />
      </el-form-item>
      <!-- 价格 -->
      <el-form-item label="价格:" prop="price">
        <el-input v-model="formDate.price" style="width:500px" />
      </el-form-item>
      <!-- 描述 -->
      <el-form-item label="描述:" prop="desc">
        <el-input v-model="formDate.desc" type="textarea" :rows="3" />
      </el-form-item>
      <el-form-item label="内容">
        <!-- 内容（富文本框） -->
        <!--
                    富文本 type为1的时候展示
                    使用插件实现：npm install vue-word-editor --save
        -->
        <!-- <VueEditor
          ref="vueEditor"
          :config="config" -->
        <template>
          <VueEditor v-model="content" />
        </template>
      </el-form-item>
      <!-- 介绍图片 -->
      <el-form-item ref="introduce" label="介绍图片" prop="photos">
        <ImageUpload ref="introduceImg" :single="false" />
      </el-form-item>
      <!-- 封面 -->
      <el-form-item label="封面" prop="image">
        <ImageUpload ref="coverImg" />
      </el-form-item>
    </el-form>
    <!-- footer插槽 -->
    <template v-slot:footer>
      <el-row type="flex" justify="center">
        <el-col :span="6">
          <el-button size="small" @click="btnCancel">取消</el-button>
          <el-button type="primary" size="small" @click="btnOk">确定</el-button>
        </el-col>
      </el-row>
    </template>
  </el-dialog>
</template>

<script>
import { VueEditor } from 'vue2-editor'
import axios from 'axios'
import ImageUpload from '@/components/ImageUpload'
import { addProperty, editProperty, getMap } from '@/api/property'
import { ListToCascaderData } from '@/utils/index'
// import { getUserInfo } from '@/api/user'
export default {
  components: {
    VueEditor,
    ImageUpload
  },
  props: {
    isClearable: {
      type: Boolean,
      default: false
    },
    showDialog: {
      type: Boolean,
      default: false
    },
    formData: {
      type: Array,
      default: null
    },
    formData1: {
      type: Array,
      default: null
    },
    echoData: {
      type: Object,
      default: null
    }
  },
  data() {
    return {
      content: '',
      userId: '',
      address: '',
      list: [],
      value1: [],
      userInfo: {},
      formDate: {
        title: '',
        tags: '',
        address: '',
        price: '',
        desc: '',
        image: '',
        photos: [],
        agent: '',
        category: '',
        id: '',
        content: ''
      },
      config: {
        // 上传图片的配置
        uploadImage: {
          url: axios.defaults.baseURL + '/upload',
          name: 'file',
          headers: {
            Authorization: localStorage.getItem('home-token')
          },
          // res是结果，insert方法会把内容注入到编辑器中，res.data.url是资源地址
          uploadSuccess(res, insert) {
            console.log(res)
            insert(axios.defaults.baseURL + res.data.data.url)
          }
        }
      },
      // 校验
      rules: {
        title: [{ required: true, message: '标题不能为空', trigger: 'blur' }],
        desc: [{ required: true, message: '描述不能为空', trigger: 'blur' }]
        // agent: [{ required: true, message: '经纪不能为空', trigger: 'change' }],
        // category: [{ required: true, message: '分类不能为空', trigger: 'change' }]
      }
    }
  },
  computed: {
    checkTitle() {
      return this.formDate.id ? '编辑房产' : '添加房产'
    }
  },
  async created() {
    const { data } = await getMap()
    // console.log(144, data.districts[0].districts)
    // this.list = data.districts[0].districts
    // data.districts[0].districts.map(item=>{

    // })
    // this.list = data.districts[0].districts
    // this.list = data.districts[0].districts.map(item => {
    //   console.log(160, item)
    //   return ListToCascaderData(item.districts)
    // })
    this.list = ListToCascaderData(data.districts[0].districts)
    // console.log(159, this.list)
  },

  methods: {
    handleChange(value) {
      console.log(value)
      this.formDate.address = value.join('')
    },
    // 弹框显示时触发
    limit() {
      // this.formDate = this.echoData

      // 回显封面
      if (this.echoData.id) {
        this.formDate = this.echoData
        console.log(196, this.formDate)
        console.log(197, this.echoData)
        this.formDate.agent = this.echoData.agent.id
        this.formDate.category = this.echoData.category.id
        // console.log(158, this.formData.id)
        if (this.formDate.image) {
          this.$refs.coverImg.fileList = [{
            url: this.formDate.image
          }]
        }
        // 回显介绍图片
        if (this.formDate.photos) {
          console.log(164, this.formDate.photos)
          for (let index = 0; index < this.formDate.photos.length; index++) {
            const list = { url: this.formDate.photos[index].url }
            this.$refs.introduceImg.fileList.push(list)
          }
        }
      } else {
        this.formDate.agent = ''
        this.formDate.category = ''
      }
    },

    // 点击确定
    async btnOk() {
      // this.$refs.introduceImg.clearFiles()
      // this.$refs.introduceImg.fileList = []
      // 校验
      try {
        await this.$refs.form.validate()
        // // 上传图片
        const fileList = this.$refs.coverImg.fileList
        const fileList1 = this.$refs.introduceImg.fileList
        console.log(183, fileList1)
        // 截取单张图片‘bolb’
        // if (fileList[0] && fileList[0].url.indexOf('blob') !== -1) {
        //   fileList[0].url.slice(5)
        // }
        // // 截取多张图片‘blob’
        // fileList1.forEach(item => {
        //   if (item.url.indexOf('blob') !== -1) {
        //     item.url.slice(5)
        //   }
        // })
        // // 判断图片是否上传完毕
        // if (fileList[0] && fileList[0].status !== 'success') {
        //   this.$message.warning('请等待图片上传完毕')
        //   return
        // }
        if (this.formDate.id) {
          console.log(233, this.formDate)
          await editProperty({ ...this.formDate, image: fileList[0] ? fileList[0].url : '', photos: fileList1.length > 0 ? fileList1 : [] })
        } else {
        // 发请求
          await addProperty({ ...this.formDate, image: fileList[0] ? fileList[0].url : '', photos: fileList1.length > 0 ? fileList1 : [] })
        }
        // 提示用户
        this.$message.success('操作成功')
        // 关闭弹窗
        this.$emit('update:showDialog', false)
        // 清空表单数据
        this.$refs.form.resetFields()
        // 清空编辑之后除表单之外的数据
        this.formDate.id = ''
        this.formDate.agent = ''
        this.formDate.category = ''
        this.formDate.address = ''
        this.formDate.content = ''
        this.$refs.coverImg.fileList = []
        // 刷新页面
        this.$emit('property')
      } catch (err) {
        console.log(err)
      }
    },
    // 点击取消
    btnCancel() {
      // 清空编辑之后，残存的id，下拉框，图片等文件
      this.$refs.coverImg.fileList = []
      this.formDate.id = ''
      this.formDate.agent = ''
      this.formDate.category = ''
      this.formDate.address = ''
      this.formDate.content = ''
      this.$refs.introduceImg.fileList = []
      // 清空实际数据
      this.formDate = {
        title: '',
        tags: '',
        address: '',
        price: '',
        desc: '',
        image: '',
        photos: [],
        agent: {
          name: ''
        },
        category: {
          title: ''
        },
        id: '',
        content: ''
      }
      // 清空表单数据
      this.$refs.form.resetFields()
      // 关闭弹窗
      this.$emit('update:showDialog', false)
      // 清空表单数据
      this.$refs.form.resetFields()
    }
  }
}
</script>

<style>

</style>
